import json
import time
import os
import pynput
from loguru import logger

# 定义小键盘的虚拟键码
numpad_vk = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105]

# 配置文件路径
CONFIG_FILE = "config.json"


class QuickTalker:
    def __init__(self):
        self.keyboard_controller = pynput.keyboard.Controller()
        self.listener = None
        self.test = 0
        self.config = self.load_config()

    def load_config(self):
        """加载配置文件"""
        try:
            with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            return {}

    def save_config(self):
        """保存配置文件"""
        try:
            with open(CONFIG_FILE, "w", encoding="utf-8") as f:
                json.dump(self.config, f, ensure_ascii=False, indent=4)
        except Exception as e:
            logger.error(f"保存配置文件失败: {e}")

    def string2gbkcode(self, string):
        """将字符串转换为GBK编码"""
        output_list = []
        try:
            for i in string:
                w = i.encode("gbk")
                n = int.from_bytes(w, byteorder="big", signed=False)
                output_list.append(str(n))
        except Exception as e:
            logger.error(e)

        return output_list

    def quick_talk(self, string, is_global=False):
        """快速喊话"""
        cut_it = string.split("\n")
        if len(cut_it) == 1:
            self.quick_talk_one_line(string, is_global)
        else:
            for i in cut_it:
                if i == "":
                    continue
                self.quick_talk_one_line(i, is_global)
                time.sleep(0.1)

    def quick_talk_one_line(self, string, is_global=False):
        """单行快速喊话"""
        gbkcode_list = self.string2gbkcode(string)

        if is_global:
            pre_button = "t"
        else:
            pre_button = "y"

        self.keyboard_controller.press(pynput.keyboard.KeyCode.from_char(pre_button))
        time.sleep(0.003)
        self.keyboard_controller.release(pynput.keyboard.KeyCode.from_char(pre_button))
        for i in gbkcode_list:
            with self.keyboard_controller.pressed(pynput.keyboard.Key.alt):
                for ii in i:
                    time.sleep(0.001)
                    self.keyboard_controller.press(
                        pynput.keyboard.KeyCode.from_vk(numpad_vk[int(ii)])
                    )
                    time.sleep(0.001)
                    self.keyboard_controller.release(
                        pynput.keyboard.KeyCode.from_vk(numpad_vk[int(ii)])
                    )
        time.sleep(0.01)
        self.keyboard_controller.press(pynput.keyboard.Key.enter)
        time.sleep(0.01)
        self.keyboard_controller.release(pynput.keyboard.Key.enter)
        self.test += 1

    def on_press(self, key):
        """键盘按键监听"""
        try:
            key_char = key.char
        except AttributeError:
            key_char = None

        if key_char and key_char in self.config:
            config_entry = self.config[key_char]
            message = config_entry.get("message", "")
            if message == "":
                logger.info("没有配置消息")
                return False
            is_global = config_entry.get("is_global", False)
            self.quick_talk(message, is_global)

    def start_listener(self):
        """启动键盘监听线程"""
        self.listener = pynput.keyboard.Listener(on_press=self.on_press)
        self.listener.start()

    def stop_listener(self):
        """停止键盘监听线程"""
        if self.listener:
            self.listener.stop()


if __name__ == "__main__":
    # 示例配置文件内容
    example_config = {
        "[": {"message": "一键喊话功能已开启！--WEGAME游戏助手", "is_global": False},
        "]": {"message": "按ALT+F4开启一键喊话", "is_global": True},
        ";": {"message": "白裤裆寒冬一击！--WEGAME", "is_global": False},
        "'": {"message": "", "is_global": False},
    }

    # 使用 os.path.exists 检测配置文件是否存在
    if not os.path.exists(CONFIG_FILE):
        logger.info("配置文件不存在，创建示例配置文件。")
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(example_config, f, ensure_ascii=False, indent=4)

    # 创建 QuickTalker 实例并启动监听
    talker = QuickTalker()
    talker.start_listener()

    try:
        while talker.listener.running:
            time.sleep(1)
    except KeyboardInterrupt:
        talker.stop_listener()